//
//  PlayVC.swift
//  TianTianBiTing
//
//  Created by Gox mac 2 on 2018/12/24.
//  Copyright © 2018 Gox_WallyDiao. All rights reserved.
//

import UIKit
import MediaPlayer

class PlayVC: TTBaseVC {
    
    var id:Int = 0
    var buyType:Int = 0
    var commentType:Int = 0
    var discussId:Int = 0
    var commentLevel1Sesion:Int = 2
    
    var centreBtn:Int = 11 // btn位置
    var partIndex:Int = 0 // 当前集位置
    var sesionCount:Int = 1 // 分集购买集数
    
    var page:Int = 1
    var totalPage:Int = 1
    var maxPage:Int = 20
    
    var detailsModel:PlayDetailsModel?
    var listModel:PlayListModel?
    var listModelArr:[PlayListModel] = [PlayListModel]()
    
    var commentModelArr:[CommentModel] = [CommentModel]()
    
    var timer:Timer?
    
    var contentLabel:UILabel = {
        let text = UILabel.init(frame: CGRect(x:15, y:7, width:200, height:18.5))
        text.font = Font_Medium(13)
        text.text = "说点什么"
        text.textColor = RGB_Same(136)
        return text
    }()
    
    var contentTextView:UITextView!
    var contentView:UIView!
    
    var keyHeight:CGFloat = 0.0
    
    var noFirst:Bool = true
    private let PlayLeftTableViewCellID = "PlayLeftTableViewCell"
    private let PlayCenterTableViewCellID = "PlayCenterTableViewCell"
    private let CommentTableViewCellID = "CommentTableViewCell"
    private let CommentHeaderViewID = "CommentHeaderView"
    
    lazy var tableView: TTTableView = {
        let tableView = TTTableView.init(frame: FRAME_CGFloat(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - OFFSET_TOP), style: UITableView.Style.plain)
        tableView.delegate = self
        tableView.dataSource = self
        tableView.backgroundColor = UIColor.white
        //        tableView.separatorStyle = UITableViewCell.SeparatorStyle.none
        tableView.bounces = true
        tableView.showsVerticalScrollIndicator = false
        tableView.showsHorizontalScrollIndicator = false
        tableView.register(NIBNAME(PlayLeftTableViewCellID), forCellReuseIdentifier: PlayLeftTableViewCellID)
        tableView.register(NIBNAME(PlayCenterTableViewCellID), forCellReuseIdentifier: PlayCenterTableViewCellID)
        tableView.register(CommentHeaderView.self, forHeaderFooterViewReuseIdentifier: CommentHeaderViewID)
        tableView.register(NIBNAME(CommentTableViewCellID), forCellReuseIdentifier: CommentTableViewCellID)
        tableView.tableFooterView = UIView.init(frame: FRAME_CGFloat(0, 0, SCREEN_WIDTH, 55))
        return tableView
    }()
    
    var redView: TimeRedPacketView?
    
    lazy var allBuyBottomView:AllBuyBottomView = {
        let all = AllBuyBottomView.init(frame: FRAME_CGFloat(0, SCREEN_HEIGHT - 54 - OFFSET_TOP, SCREEN_WIDTH, 54))
        
        return all
    }()
    
    var part:PartBuyBottomView = {
        let part = PartBuyBottomView.init(frame: FRAME_CGFloat(0, SCREEN_HEIGHT - OFFSET_TOP - 250, SCREEN_WIDTH, 250))
        return part
    }()
    
    lazy var bcView:UIView! = {
        let bcView = UIView()
        return bcView
    }()
    
    deinit {
        if self.bcView != nil {
            self.bcView.removeFromSuperview()
            self.bcView = nil
        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        UIApplication.shared.beginReceivingRemoteControlEvents()
        self.becomeFirstResponder()
        self.view.backgroundColor = WhiteBackColor
        
        setData()
        self.view.addSubview(self.tableView)
        
        setContentView()
        self.addkeyBoardObserver(tagView: self.contentView)
        
        
        TTNotificationCenter.addNotificatioin(ReloadPlayVcData) { (obj) in
            self.tableView.reloadData()
        }
        
        TTNotificationCenter.addNotificatioin(Music_Play) { (obj) in
            self.setBackground()
        }
        
        TTNotificationCenter.addNotificatioin(Music_Next) { (obj) in
            self.autoNextSongAction()
            
        }
        
        TTNotificationCenter.addNotificatioin(RefreshPlayVcData) { (obj) in
            self.refreshData()
        }
        
        self.tableView.initMjFooterWithOffest(0) { (taleView) in
            if self.centreBtn == 12 {
                self.page = self.page + 1
                self.setListData()
            } else if self.centreBtn == 13 {
                self.tableView.endAllRefreshing()
            }
            
        }
        
        self.tableView.initMjHeaderWithOffest(0) { (tableView) in
            if self.centreBtn == 12 {
                self.page = 1
                self.detailsModel = nil
                self.listModelArr = [PlayListModel]()
                self.tableView.reloadData()
                self.setData()
            } else if self.centreBtn == 13 {
                self.contentLabel.text = "说点什么"
                self.setCommentData()
            }
            
        }
        
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        self.redView = TimeRedPacketView.init(frame: FRAME_CGFloat(SCREEN_WIDTH - 80, 300, 80, 80), viewName: "详情页")
        self.view.addSubview(self.redView!)
        
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        
        self.redView?.removeFromSuperview()
    }
    
    override var canBecomeFirstResponder: Bool {
        return true
    }
    
    
}

//  MARK: - ###### UI ######
extension PlayVC: UITextFieldDelegate, UITextViewDelegate {
    func setContentView() {
        
        self.contentView = UIView(frame: CGRect(x:0, y:SCREEN_HEIGHT - 54 - OFFSET_TOP, width:SCREEN_WIDTH, height:54))
        self.contentView.backgroundColor = UIColor.white
        self.contentView.isHidden = true
        self.view.addSubview(self.contentView)
        //        self.contentView.addSubview(self.contentTextField)
        //        self.contentView.isHidden = true
        
        self.contentTextView = UITextView.init(frame: CGRect(x:15, y:5, width:SCREEN_WIDTH - 30, height:34))
        self.contentTextView.delegate = self
        self.contentTextView.isScrollEnabled = true
        self.contentTextView.scrollsToTop = false
        self.contentTextView.returnKeyType = .send
        self.contentTextView.layer.cornerRadius = 17
        self.contentTextView.font = Font_Medium(13)
        self.contentTextView.backgroundColor = RGB_Same(240)
        self.contentView.addSubview(self.contentTextView)
        self.contentTextView.addSubview(self.contentLabel)
        SET_LINEVIEW(view: self.contentView)

    }
    
    func textViewDidChange(_ textView: UITextView) {
        if textView.text != "" {
            self.contentLabel.isHidden = true
        } else {
            self.contentLabel.isHidden = false
        }

    }
    
    func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
        if text == "\n" {
            self.sendAction()
        }
        if text != " " && range.length > 0 {
            return true
        } else {
            if NSString(string: textView.text).length - range.length + NSString(string: text).length > 100 {
                TTAlertView.showMessage(message: "超出最大长度100！")
                return false
            } else {
                return true
            }
        }
    }
    
    func sendAction() {
        self.contentTextView.resignFirstResponder()
        if contentTextView.text != "" {
            if self.commentType == 0 {
                HomeRequestModel.UpdateDiscussProgram(parameters: ["content": self.contentTextView.text, "programId": self.id, "userId": String.getUserId()]) { (success, message) in
                    if success {
                        TTAlertView.showMessage(message: "评论成功")
                        
                        self.setCommentData()
                    } else {
                        TTAlertView.showMessage(message: message)
                    }
                }
            } else {
                HomeRequestModel.UpdateDiscussProgram(parameters: ["content": self.contentTextView.text, "discussId": self.discussId, "programId": self.id, "userId": String.getUserId()]) { (success, message) in
                    if success {
                        TTAlertView.showMessage(message: "评论成功")
                        
                        self.setCommentData()
                    } else {
                        TTAlertView.showMessage(message: message)
                    }
                }
            }
        }
        
    }
    
    
}

//  MARK: - ###### 数据请求 ######
extension PlayVC {
    // 最新数据
    func setData() {
        MTProgressHUD.show()
        HomeRequestModel.loadPlayDetailsData(programId: [id, String.getUserId()]) { (success, message, model) in
            if success && model != nil {
                self.detailsModel = model!
                TTAudioPlayer.indextNum = (self.detailsModel?.currentSeason)! - 1
//                TTAudioPlayer.progressDoub = (self.detailsModel?.progress)!
                TTAudioPlayer.progressDoub = self.getProgress(id: self.id)
                self.navigationItem.title = self.detailsModel?.title ?? ""
                self.setListData()
            }
            if model == nil {
                self.tableView.setNoData(nodata: true)
            } else {
                self.tableView.setNoData(nodata: false)
            }
            MTProgressHUD.hidded(true)
        }
    }
    
    func setListData() {
        if (self.detailsModel?.currentSeason)! > self.maxPage {
            self.maxPage = (self.detailsModel?.currentSeason)!
        }
        if self.page <= self.totalPage {
            
            if self.page == 1 {
                self.listModelArr = [PlayListModel]()
            }
            
            let para = ["userId":String.getUserId(),"startPoint": self.page,"maxPage": self.maxPage]
            MTProgressHUD.show()
            HomeRequestModel.loadPlayListData(programId: id, parameters: para) { (success, message, model, page) in
                if success && model != nil {
                    self.totalPage = page!
                    for dic in model! {
                        self.listModelArr.append(dic)
                    }
                    
                }
                self.tableView.reloadData()
                self.showBottomView()
                MTProgressHUD.hidded(true)
            }
        }
        self.tableView.endAllRefreshing()
    }
    
    func setCommentData() {
        MTProgressHUD.show()
        HomeRequestModel.loadDiscussData(parameters: ["programId":self.id,"startPoint": 1,"maxPage": 9999]) { (success, message, model) in
            if success && model != nil {
                self.commentModelArr = model!
                self.tableView.reloadData()
                self.setInitComment()
            }
            MTProgressHUD.hidded(true)
            if self.commentModelArr.count == 0 {
                self.tableView.setNoData(nodata: true, offY: 169 + SCREEN_SCALE_X(x: 188))
            } else {
                self.tableView.setNoData(nodata: false, offY: 169 + SCREEN_SCALE_X(x: 188))
            }
        }
        self.tableView.endAllRefreshing()
    }
    
    func setCommentLevel1Data() {
        if self.commentModelArr[self.commentLevel1Sesion - 2].open {
            self.commentModelArr[self.commentLevel1Sesion - 2].setIsOpen()
            self.setInitComment()
            self.tableView.reloadData()
            
        } else {
            MTProgressHUD.show()
            HomeRequestModel.loadDiscussLevel1Data(parameters: ["discussId":self.discussId]) { (success, message, model) in
                if success && model != nil {
                    self.commentModelArr[self.commentLevel1Sesion - 2].setChildComment(model: model!)
                    self.commentModelArr[self.commentLevel1Sesion - 2].setIsOpen()
                    self.tableView.reloadData()
                }
                MTProgressHUD.hidded(true)
            }
        }
        
    }
    
    func getProgress(id:Int) -> Double {
        var dic = UserDefaults.standard.dictionary(forKey: PlayDictionary)
        if dic!["\(id)"] != nil {
            return dic!["\(id)"] as! Double
        } else {
            return 0.0
        }
    }
    
    func setInitComment() {
        self.contentTextView.text = ""
        self.contentLabel.isHidden = false
        self.contentLabel.text = "说点什么"
        self.commentType = 0
        self.discussId = 0
    }
    
}

//  MARK: - ###### 播放相关 ######
extension PlayVC {
    func setBackground() {
        //        let nData = NSData.init(contentsOf: URLSTR(StringIncludeChineseToString(TTAudioPlayer.imageUrl!)))
        //        let image = UIImage.init(data: nData! as Data)
        //
        //        let settings = [MPMediaItemPropertyTitle: TTAudioPlayer.activeMusic?.title ?? "" as Any,
        //                        MPMediaItemPropertyArtist: TTAudioPlayer.activeMusic?.describe ?? "" as Any,
        //                        MPMediaItemPropertyPlaybackDuration: TTAudioPlayer.audioPlayer.duration,
        //                        MPNowPlayingInfoPropertyElapsedPlaybackTime: TTAudioPlayer.audioPlayer.progress,
        //                        MPMediaItemPropertyArtwork: MPMediaItemArtwork(image: image!)] as [String : Any]
        //        MPNowPlayingInfoCenter.default().setValue(settings, forKey: "nowPlayingInfo")
    }
    
    override func remoteControlReceived(with event: UIEvent?) {
        self.setBackground()
        if event?.type == UIEvent.EventType.remoteControl {
            switch event!.subtype {
            case .remoteControlPreviousTrack:
                //                TTAudioPlayer.playPreviousSong()
                self.playNextBtnAction(tag: 21)
            case .remoteControlNextTrack:
                self.playNextBtnAction(tag: 22)
            //                TTAudioPlayer.playNextSong()
            case .remoteControlPlay:
                TTAudioPlayer.resume()
            case .remoteControlPause:
                TTAudioPlayer.pause()
            default:
                break
            }
        }
        self.tableView.reloadData()
    }
    
    @objc fileprivate func stopPlay() {
        TTAudioPlayer.pause()
        self.timer = nil
        self.timer?.invalidate()
        self.tableView.reloadData()
    }
    
    func setPlay() {
        TTAudioPlayer.uploadDate()
        TTAudioPlayer.isSelected = true
        TTAudioPlayer.uploadProgress()
        TTAudioPlayer.programId = (self.detailsModel?.id)!
        TTAudioPlayer.play()
        self.tableView.reloadData()
    }
    
}

//  MARK: - ###### 事件 ######
extension PlayVC {
    func shareAction() {
        HomeRequestModel.loadResourcesData(parameters: ["flg":"go_download"]) { (success, message, urlStr) in
            if success {
                let newUrl = urlStr + "?srcUserId=\(String.getUserId())"
                let share = ShareView.init(frame: FRAME_CGFloat(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT), title: self.detailsModel?.title ?? "天天必听", des: self.detailsModel?.describe ?? "分享免费听", url: newUrl ?? "https://itunes.apple.com/cn/app/天天必听/id1449930721", image: self.detailsModel?.shareImageUrl ?? "http://source.blistening.cn/bt_source/ttbt/logo/logo.png")
                UIApplication.shared.keyWindow?.addSubview(share)
            }
        }
    }
}

//  MARK: - ###### 购买相关 ######
extension PlayVC {
    func showBottomView() {
        if (self.detailsModel != nil) {
            if self.detailsModel?.category == 0 {
                
            } else {
                if self.detailsModel?.everySeasonBuy == 0 { //全集
                    if self.listModelArr[0].buySelf == 0 {
                        self.allBuyBottomView.leftLabel.text = "\(String.money(self.detailsModel!.totalCount)!)听币"
                        self.allBuyBottomView.delegate = self
                        self.view.addSubview(self.allBuyBottomView)
                    } else {
                        self.allBuyBottomView.removeFromSuperview()
                    }
                } else { // 单机购买
                    self.part.delegate = self
                    self.view.addSubview(part)
                    self.part.isHidden = true
                }
            }
        }
    }
    
    func confirmPurchase() {
        if buyType == 1 { // 全集购买
            HomeRequestModel.buyAllSeason(parameters: ["userId":String.getUserId(),"programId":TTAudioPlayer.programId,"balance":self.detailsModel?.totalCount]) { (success, message, state) in
                if success {
                    TTAlertView.showMessage(message: message)
                    TTNotificationCenter.Post(RefreshPlayVcData, obj: nil)
                } else {
                    if state == "2" {
                        TTAlertView.ask(title: nil, question: message, leftTitle: "取消", rightTitle: "充值", okBlock: {
                            let wal = WalletVc()
                            PUSHVIEWCONTROLLER(wal)
                        }, noBlock: {
                            
                        })
                    } else {
                        TTAlertView.showMessage(message: message)
                    }
                }
            }
        } else if buyType == 2 { // 分级购买
            var arr:[Int] = [Int]()
            if sesionCount == 1 {
                let currentId = "\(self.listModelArr[partIndex].id)"
                HomeRequestModel.buyPartSeason(parameters: ["userId":String.getUserId(),"programId":id,"seasonIds":currentId]) { (success, message, state) in
                    if success {
                        TTAlertView.showMessage(message: message)
                        TTNotificationCenter.Post(RefreshPlayVcData, obj: nil)
                    } else {
                        if state == "2" {
                            TTAlertView.ask(title: nil, question: message, leftTitle: "取消", rightTitle: "充值", okBlock: {
                                let wal = WalletVc()
                                PUSHVIEWCONTROLLER(wal)
                            }, noBlock: {
                                
                            })
                        } else {
                            TTAlertView.showMessage(message: message)
                        }
                    }
                }
            } else if sesionCount == 10 {
                //                for i in partIndex..<partIndex + 9 {
                //                    arr = arr + [self.listModelArr[i].id]
                //                }
                let currentId = self.listModelArr[partIndex].id
                HomeRequestModel.buy10Season(parameters: ["userId":String.getUserId(),"currentSeasonId":currentId,"sort":0]) { (success, message, state) in
                    if success {
                        TTAlertView.showMessage(message: message)
                        TTNotificationCenter.Post(RefreshPlayVcData, obj: nil)
                    } else {
                        if state == "2" {
                            TTAlertView.ask(title: nil, question: message, leftTitle: "取消", rightTitle: "充值", okBlock: {
                                let wal = WalletVc()
                                PUSHVIEWCONTROLLER(wal)
                            }, noBlock: {
                                
                            })
                        } else {
                            TTAlertView.showMessage(message: message)
                        }
                    }
                }
            } else {
                return
            }
        }
    }
    
    func closePayOrderView() {
        self.bcView.removeFromSuperview()
    }
    
    func createPayOrderView() {
        let bView = PayOrderDetailsView.init(frame: UIScreen.main.bounds)
        bView.delegate = self
        if self.buyType == 1 {
            bView.setData(imageStr: self.detailsModel?.shareImageUrl ?? "", albumStr: self.detailsModel?.title ?? "", numberStr: "全集", priceStr: "\(String.money(self.detailsModel?.totalCount ?? 0) ?? "0")听币")
        } else if self.buyType == 2 {
            bView.setData(imageStr: self.detailsModel?.shareImageUrl ?? "", albumStr: self.detailsModel?.title ?? "", numberStr: self.part.topLabel.text!, priceStr: self.part.moneyLabel.text!)
        } else {
            return
        }
        self.bcView = bView
        UIApplication.shared.keyWindow?.addSubview(self.bcView)
        
    }
    
}

//  MARK: - ###### OtherView协议 ######
extension PlayVC: PlayCentreViewDelegate, PlayHeaderViewDelegate, BuyRightBtnDelegate, PartBuyBottomViewDelegate, PayOrderDetailsViewDelegate {
    func btnAction(tag: Int) {
        switch tag {
        case 101:
            HomeRequestModel.loadWXPicData(parameters: ["type":1]) { (success, message, url) in
                if success {
                    let serviceView = ServiceView.init(frame: FRAME_CGFloat(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - OFFSET_TOP))
                    serviceView.imageView?.sd_setImage(with: URL(string: StringIncludeChineseToString(url ?? "")), completed: nil)
                    self.view.addSubview(serviceView)
                } else {
                    TTAlertView.showMessage(message: "请稍后再试！")
                }
            }
        case 102:
            shareAction()
        case 103:
            TTAlertView.showMessage(message: "暂未开放，尽情期待！", second: 2)
        default:
            return
        }
    }
    
    func payOrderDetailsViewAction(tag: Int) {
        if tag == 31 {
            //            self.closePayOrderView()
        } else if tag == 32 {
            self.confirmPurchase()
        } else {
            
        }
        self.bcView.removeFromSuperview()
    }
    
    func timeBtnAction() {
        let alertController = UIAlertController(title: nil, message: "请选择定时关闭时间", preferredStyle: UIAlertController.Style.alert)
        let alertView0 = UIAlertAction(title: "不开启", style: UIAlertAction.Style.default) { (UIAlertAction) -> Void in
            self.timer = nil
            self.timer?.invalidate()
        }
        let alertView1 = UIAlertAction(title: "10分钟后", style: UIAlertAction.Style.default) { (a) -> Void in
            self.timer = Timer.scheduledTimer(timeInterval: 600, target: self, selector: #selector(self.stopPlay), userInfo: nil, repeats: false)
        }
        let alertView2 = UIAlertAction(title: "30分钟后", style: UIAlertAction.Style.default) { (UIAlertAction) -> Void in
            self.timer = Timer.scheduledTimer(timeInterval: 1800, target: self, selector: #selector(self.stopPlay), userInfo: nil, repeats: false)
        }
        let alertView3 = UIAlertAction(title: "1小时后", style: UIAlertAction.Style.default) { (UIAlertAction) -> Void in
            self.timer = Timer.scheduledTimer(timeInterval: 3600, target: self, selector: #selector(self.stopPlay), userInfo: nil, repeats: false)
        }
        let alertView4 = UIAlertAction(title: "关闭", style: UIAlertAction.Style.cancel) { (UIAlertAction) -> Void in
        }
        
        alertController.addAction(alertView0)
        alertController.addAction(alertView1)
        alertController.addAction(alertView2)
        alertController.addAction(alertView3)
        alertController.addAction(alertView4)
        self.present(alertController, animated: true, completion: nil)
    }
    
    func playNextBtnAction(tag: Int) {
        let indMax = self.listModelArr.count - 1
        var ind = TTAudioPlayer.indextNum
        if tag == 21 {
            if ind == 0 {
                ind = indMax
            } else {
                ind = ind - 1
            }
        } else if tag == 22 {
            if ind == indMax {
                ind = 0
            } else {
                ind = ind + 1
            }
        }
        
        if self.listModelArr[ind].buySelf == 0 && self.listModelArr[ind].tryStatus == 1 {
            TTAlertView.showMessage(message: "需要先购买才能试听哦")
        } else {
            
            TTAudioPlayer.indextNum = ind
            TTAudioPlayer.activeMusiclist = self.listModelArr[TTAudioPlayer.indextNum]
            
            self.setPlay()
        }
    }
    
    func autoNextSongAction() {
        if self.id == TTAudioPlayer.programId {
            let indMax = self.listModelArr.count - 1
            var ind = TTAudioPlayer.indextNum
            if ind == indMax {
                ind = 0
            } else {
                ind = ind + 1
            }
            
            if self.listModelArr[ind].buySelf == 0 && self.listModelArr[ind].tryStatus == 1 {
                TTAlertView.showMessage(message: "需要先购买才能试听哦")
            } else {
                
                TTAudioPlayer.indextNum = ind
                TTAudioPlayer.activeMusiclist = self.listModelArr[TTAudioPlayer.indextNum]
                
                self.setPlay()
            }
            
        }
    }
    
    func BuyRightBtnAction() { // 全集购买
        self.buyType = 1
        self.createPayOrderView()
    }
    
    func refreshData() {
        self.page = 1
        self.detailsModel = nil
        self.listModelArr = [PlayListModel]()
        //        self.tableView.beginHeadRefresh()
        self.setData()
    }
    
    func buyBtnActionDele() { // 分级购买
        self.buyType = 2
        self.createPayOrderView()
        
    }
    
    func centreBtnActionDele(tag: Int) {
        switch tag {
        case 31:
            self.sesionCount = 1
            self.part.topLabel.text = "第\(self.listModelArr[self.partIndex].season ?? "0")集"
            self.part.moneyLabel.text = "\(String.money(self.listModelArr[self.partIndex].price ?? 0) ?? "0")听币"
        case 32:
            self.sesionCount = 10
            HomeRequestModel.get10SeasonCount(parameters: ["programId":id]) { (count) in
                var p = 0
                let n = count - self.partIndex - 1
                if n < 10 {
                    p = self.partIndex + n + 1
                } else {
                    p = self.partIndex + 10
                }
                
                self.part.topLabel.text = "第\(self.listModelArr[self.partIndex].season ?? "0")~\(p)集"
            }
            HomeRequestModel.get10SeasonPrice(parameters: ["programId":id,"seasonId":self.listModelArr[self.partIndex].id,"sort":0]) { (price) in
                self.part.moneyLabel.text = "\(String.money(price) ?? "0")听币"
            }
            
        case 33:
            let vc = PartPayVc()
            vc.programId = id
            //            vc.price = self.listModelArr[self.partIndex].price ?? 0
            PUSHVIEWCONTROLLER(vc)
        default:
            return
        }
    }
    
    func playHeaderViewAction() {
        if self.listModelArr.count == 0 {
            self.tableView.setNoData(nodata: true)
        } else {
            self.tableView.setNoData(nodata: false)
        }
        self.centreBtn = 12
        self.contentView.isHidden = true
        self.tableView.reloadData()
        self.tableView.scrollToRow(at: NSIndexPath.init(row: 0, section: 1) as IndexPath, at: .top, animated: true)
    }
    
    func playCentreViewAction(state: Int) {
        if self.listModelArr.count == 0 {
            self.tableView.setNoData(nodata: true)
        } else {
            self.tableView.setNoData(nodata: false)
        }
        self.centreBtn = state
        self.contentTextView.resignFirstResponder()
        self.tableView.reloadData()
        self.contentView.isHidden = true
        if state == 12 {
            
            let scrollToIndex:IndexPath = IndexPath.init(row: TTAudioPlayer.indextNum, section: 1)
            self.tableView.scrollToRow(at: scrollToIndex, at: .middle, animated: true)
        } else if state == 13 {
            self.contentView.isHidden = false
            self.setCommentData()
        }
    }
    
}

//  MARK: - ###### TableView协议 ######
extension PlayVC: UITableViewDelegate, UITableViewDataSource {
    func numberOfSections(in tableView: UITableView) -> Int {
        
        switch self.centreBtn {
        case 11:
            return 2
        case 12:
            return 2
        case 13:
            return self.commentModelArr.count + 2
        default:
            return 0
        }
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        switch self.centreBtn {
        case 11:
            if section == 0 {
                return 0
            } else {
                return 1
            }
        case 12:
            if section == 0 {
                return 0
            } else {
                return self.listModelArr.count
            }
        case 13:
            if section == 0 || section == 1 {
                return 0
            } else {
                if self.commentModelArr[section - 2].open {
                    return self.commentModelArr[section - 2].childCommentModel?.count ?? 0
                } else {
                    return 0
                }
            }
        default:
            return 0
        }
        
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        switch self.centreBtn {
        case 11:
            return SCREEN_HEIGHT
        case 12:
            return 72.5
        case 13:
            return UITableView.automaticDimension
        default:
            return 0
        }
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        switch self.centreBtn {
        case 11:
            if indexPath.section == 0 {
                return UITableViewCell.init()
            } else {
                let cell = tableView.dequeueReusableCell(withIdentifier: PlayLeftTableViewCellID) as! PlayLeftTableViewCell
                cell.backgroundColor = .white
                cell.playWebView.loadHTMLString(self.detailsModel?.describe ?? "", baseURL: nil)
                cell.selectionStyle = .none
                self.tableView.separatorStyle = .none
                return cell
            }
        case 12:
            if indexPath.section == 0 {
                return UITableViewCell.init()
            } else {
                let cell = tableView.dequeueReusableCell(withIdentifier: PlayCenterTableViewCellID) as! PlayCenterTableViewCell
                cell.everySeasonBuy = self.detailsModel?.everySeasonBuy ?? 0
                cell.modelList = self.listModelArr[indexPath.row]
                self.tableView.separatorStyle = .none
                if indexPath.row == TTAudioPlayer.indextNum {
                    cell.titleLabel.textColor = TabbarTintColor
                } else {
                    cell.titleLabel.textColor = BlackBackColor
                }
                cell.selectionStyle = .none
                cell.selectionStyle = .none
                return cell
            }
        case 13:
            if indexPath.section == 0  || indexPath.section == 1 {
                return UITableViewCell.init()
            } else {
                let cell = tableView.dequeueReusableCell(withIdentifier: CommentTableViewCellID) as! CommentTableViewCell
                let model = self.commentModelArr[indexPath.section - 2].childCommentModel?[indexPath.row]
                
                let attrs1 = [NSAttributedString.Key.font : Font_Medium(13), NSAttributedString.Key.foregroundColor : RGB(255, 151, 29)]
                let attrs2 = [NSAttributedString.Key.font : Font_Medium(13), NSAttributedString.Key.foregroundColor : RGB_Same(53)]
                let attributedString1 = NSMutableAttributedString(string:model?.user?.wxNickname ?? "", attributes:attrs1 as [NSAttributedString.Key : Any])
                let attributedString2 = NSMutableAttributedString(string:"：\(model?.content ?? "")", attributes:attrs2 as [NSAttributedString.Key : Any])
                attributedString1.append(attributedString2)
                cell.commentLabel.attributedText = attributedString1
                cell.selectionStyle = .none
                return cell
            }
        default:
            return UITableViewCell.init()
        }
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        self.contentTextView.resignFirstResponder()
        switch self.centreBtn {
        case 11:
            print("11")
        case 12:
            if self.listModelArr[indexPath.row].buySelf == 0 && self.listModelArr[indexPath.row].tryStatus == 1 {
                TTAlertView.showMessage(message: "需要先购买才能试听哦")
                self.part.isHidden = false
                self.part.topLabel.text = "第\(self.listModelArr[indexPath.row].season ?? "0")集"
                self.part.moneyLabel.text = "\(String.money(self.listModelArr[indexPath.row].price ?? 0) ?? "0")听币"
                self.partIndex = indexPath.row
                self.sesionCount = 1
                self.part.setFirstChoose()
            } else {
                self.part.isHidden = true
                TTAudioPlayer.indextNum = indexPath.row
                TTAudioPlayer.isIndextNum = indexPath.row
                TTAudioPlayer.activeMusiclist = self.listModelArr[indexPath.row]
                TTAudioPlayer.activeMusicArr = self.listModelArr
                self.setPlay()
                
            }
        case 13:
            print("13")
        default:
            return
        }
        
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        switch section {
        case 0:
            return 125 + SCREEN_SCALE_X(x: 188)
        case 1:
            return 34
        default:
            switch self.centreBtn {
            case 11:
                return 0
            case 12:
                return 0
            case 13:
                return UITableView.automaticDimension
            default:
                return 0
            }
        }
    }
    
    func tableView(_ tableView: UITableView, estimatedHeightForHeaderInSection section: Int) -> CGFloat {
        switch section {
        case 0:
            return 125 + SCREEN_SCALE_X(x: 188)
        case 1:
            return 34
        default:
            switch self.centreBtn {
            case 11:
                return 0
            case 12:
                return 0
            case 13:
                return 50
            default:
                return 0
            }
        }
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        switch section {
        case 0:
            if self.detailsModel != nil {
                let playView = PlayHeaderView.init(frame: FRAME_CGFloat(0, 0, SCREEN_WIDTH, 125 + SCREEN_SCALE_X(x: 188)))
                playView.programId = self.detailsModel?.id ?? 0
                playView.musicModel = self.listModelArr[TTAudioPlayer.indextNum]
                playView.playTrackInfo = self.detailsModel
                playView.delegate = self
                
                return playView
            } else {
                return UIView.init()
            }
        case 1:
            if self.detailsModel != nil {
                let centre = PlayCentreView.init(frame: FRAME_CGFloat(0, 0, SCREEN_WIDTH, 44))
                centre.btnTag(tag: self.centreBtn)
                centre.delegate = self
                return centre
            } else {
                return UIView.init()
            }
        default:
            switch self.centreBtn {
            case 11:
                return UIView.init()
            case 12:
                return UIView.init()
            case 13:
                let header = tableView.dequeueReusableHeaderFooterView(withIdentifier: CommentHeaderViewID) as! CommentHeaderView
                let model = self.commentModelArr[section - 2]
                let user = model.user
                header.headImage.sd_setImage(with: URL(string:(StringIncludeChineseToString(user?.wxAvatarUrl ?? ""))), placeholderImage: IMAGE(name: "Mine_head"), options: .lowPriority, completed: nil)
                header.nameLabel.text = user?.wxNickname
                header.contentLabel.text = model.content
                header.timeLabel.text = model.createTimeStr
                header.numberLabel.text = "\(model.countDiscuss)"
                header.headBlock = { () in
                    self.contentTextView.resignFirstResponder()
                    self.contentTextView.text = ""
                    self.contentLabel.isHidden = false
                    self.contentLabel.text = "回复：\(user?.wxNickname ?? "")"
                    self.commentType = 1
                    self.discussId = model.id
                    self.commentLevel1Sesion = section
                    self.setCommentLevel1Data()
                }
                return header
            default:
                return UIView.init()
            }
        }
    }
}

